import { routerRedux } from 'dva/router';
import { stringify } from 'querystring';
import { login, getFakeCaptcha, loginNew } from '@/services/login';
import { setAuthority } from '@/utils/authority';
import { getPageQuery } from '@/utils/utils';
import { message } from 'antd';

const Model = {
  namespace: 'login',
  state: {
    status: undefined,
    currentInfo: {},
  },
  effects: {
    *login({ payload }, { call, put }) {
      const response = yield call(loginNew, payload);

      // Login successfully
      if (response.code == 0) {  
        yield put({
          type: 'save',
          payload: {
            currentInfo: response.data[0].sysUser,
            user: response.data[0],
          }
        })
        payload.autoLogin ? 
        localStorage.setItem('user', JSON.stringify(response.data[0])) :
        sessionStorage.setItem('user', JSON.stringify(response.data[0]))

        yield put(routerRedux.replace('/'));
      } else {
        message.error(response.msg)
      }
    },

    *getCaptcha({ payload }, { call }) {
      yield call(getFakeCaptcha, payload);
    },

    *logout(_, { put }) {
      localStorage.removeItem('user')
      sessionStorage.removeItem('user')
      localStorage.removeItem('hasSearchBtn')
      if (window.location.pathname !== '/user/login') {
        yield put(
          routerRedux.replace({
            pathname: '/user/login',
          }),
        );
      }
    },
  },
  reducers: {
    save(state, { payload }) {
      return {
        ...state,
        ...payload,
      }
    },
    changeLoginStatus(state, { payload }) {
      setAuthority(payload.currentAuthority);
      return { ...state, status: payload.status, type: payload.type };
    },
  },
};
export default Model;
